﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using Predica.FimCommunication.Export;

namespace Predica.FimExplorer.UI.WPF.Main
{
    public partial class MainWindow : Window
    {
        MainModel _model;
        ReferenceColumnDetector _referenceColumnDetector;
        WindowsManager _windowsManager;

        public MainWindow()
        {
            try
            {
                _windowsManager = new WindowsManager();
                _model = new MainModel(this, FimClientFactory.CreateClient(), _windowsManager, new XmlExporter());
                _referenceColumnDetector = new ReferenceColumnDetector();

                InitializeComponent();

                this.DataContext = _model;
                _model.Initialize();
            }
            catch (Exception exc)
            {
                MessageBox.Show(@"There was an error during application startup. Verify that your configuration file points to a valid FIM service instance.
Application will now close.

Exception details:

" + exc, "Predica.FimExplorer Initialization error", MessageBoxButton.OK, MessageBoxImage.Error);

                Application.Current.Shutdown();
            }
        }

        private void btnRunQuery_Click(object sender, RoutedEventArgs e)
        {
            if (_model.CurrentAttributes.Count == 0)
            {
                _windowsManager.Error("Object type must be selected first. Only currently selected object type can be searched by xpath.");
                return;
            }

            try
            {
                _model.ExecuteQuery();
            }
            catch (Exception exc)
            {
                _windowsManager.Error(exc.ToString());
            }
        }

        private void btnFindById_Click(object sender, RoutedEventArgs e)
        {
            _model.ShowDetailsById();
        }

        private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            // only references are marked as objects, all other are strings
            _referenceColumnDetector.ProcessAutogeneratedColumn<object>(e
                , id =>
                {
                    _model.IdForSearch = id;
                    _model.ShowDetailsById();
                });

            DecideColumnOrder(e);
        }

        // field used to correctly set column display indexes (ID and DisplayName); reset when all columns are generated
        private bool resourceID_column_already_configured = false;

        private void DecideColumnOrder(DataGridAutoGeneratingColumnEventArgs e)
        {
            // ObjectID always as 1st column
            if (e.PropertyName == "Resource ID")
            {
                e.Column.DisplayIndex = 0;
                resourceID_column_already_configured = true;
            }
            // DisplayName is 2nd
            if (e.PropertyName == "Display Name")
            {
                // set to 0 if ResourceID was not already configured - it will be configured later, pushing this column further
                e.Column.DisplayIndex = resourceID_column_already_configured ? 1 : 0;
            }
        }

        private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
        {
            resourceID_column_already_configured = false;
        }

        private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _model.ShowDetailsById();
        }

        private void btnExportXml_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog();
                saveFileDialog.DefaultExt = ".xml";
                saveFileDialog.Filter = "XML documents|*.xml|All files|*.*";

                if (saveFileDialog.ShowDialog() != true)
                {
                    return;
                }

                _model.ExportToXml(saveFileDialog.FileName);

                _windowsManager.Info("Export finished");
            }
            catch (Exception exc)
            {
                _windowsManager.Error(exc.ToString());
            }
        }

        private void btnImportXml_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openFileDialog = new OpenFileDialog();
                openFileDialog.DefaultExt = ".xml";
                openFileDialog.Filter = "XML documents|*.xml|All files|*.*";

                if (openFileDialog.ShowDialog() != true)
                {
                    return;
                }

                _windowsManager.ImportObjectsDialog(openFileDialog.FileName);
            }
            catch (Exception exc)
            {
                _windowsManager.Error(exc.ToString());
            }
        }
    }
}
